/*
 * Copyright 2010
 * Jairou Software Organization
 * All Rights Reserved.
 * 
 * This software is the proprietary 
 * information of Roger Ramia
 * and the Jairou Software Organization 
 * Use is subject to license terms.
 * 
 * For licensing information please visit
 * http://www.jairou.org/license
 * 
 * @author Roger Ramia
 */
package org.jairou.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jairou.core.Strings;
import org.jairou.core.XML;

public class ViewServlet
extends HttpServlet {
	
	/**
	 * serial version id
	 */
	private static final long serialVersionUID = -8419183542219790382L;
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) 
	throws ServletException {
		this.doPost(req, resp);
	}
	
	/**
	 * still under development
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp) 
	throws ServletException {
		try {
			String id = Web.getId(req);
			String template = XML.get("view."+id+".template");
			if (template != null) {
				String content = XML.get("view."+id+".content");
				if (Strings.nullOrEmpty(content)) content = "text/html";
				resp.setContentType(content);
				
				String[] panels = XML.getIds("view."+id+".panel");
				if (panels != null && panels.length > 0) {
					Map<String, String> view = new HashMap<String, String>();
					for(String panel : panels) {
						String val = XML.get("view."+id+".panel."+panel);
						view.put(panel, val);
						req.setAttribute("view", view);
					}					
				}				
				req.getRequestDispatcher(template).include(req, resp);
			}
			else resp.sendError(404);
		}
		catch(Exception e) {
			throw new ServletException(e);
		}
	}
}